package com.rimi.controller;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.nimbusds.jose.JOSEException;
import com.rimi.bean.Code;
import com.rimi.bean.CompanyInfoBean;
import com.rimi.bean.YqzcInvoice;
import com.rimi.bean.YqzcUser;
import com.rimi.commons.CommonResult;
import com.rimi.commons.ResultStatus;
import com.rimi.model.dto.CompanyInfoDto;
import com.rimi.model.dto.LoginDto;
import com.rimi.model.vo.*;
import com.rimi.service.CodeService;
import com.rimi.service.CompanyService;
import com.rimi.service.InvoiceService;
import com.rimi.service.UserService;
import com.rimi.util.JwtUtil;
import com.rimi.util.shortMessageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * @author 罗晨
 * @version V1.0
 * @Description: 用一句话描述该文件做什么
 * @date 2021 2021/7/3 17:17
 */
@Slf4j
@RestController
@Api(description = "用户管理",tags = "用户管理")
@CrossOrigin
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    CompanyService companyService;

    @Autowired
    InvoiceService invoiceService;

    @Autowired
    CodeService codeService;

    private final LoginDto loginDto = new LoginDto();

    @PostMapping("/login")
    @ApiOperation("密码登录")
    public CommonResult login(@RequestBody LoginVo loginVo){

        YqzcUser userByUserPhoneNumber = userService.findUserByUserPhoneNumber(loginVo.getUserPhoneNumber());
        if (userByUserPhoneNumber == null){
            return CommonResult.onFailed(ResultStatus.NOTFIND_USER);
        }
        Subject subject= SecurityUtils.getSubject();

        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(loginVo.getUserPhoneNumber(),loginVo.getUserPassword());

        try {
            subject.login(usernamePasswordToken);
            YqzcUser yqzcUser=(YqzcUser) subject.getPrincipal();
            if (yqzcUser == null){
                return CommonResult.onFailed(ResultStatus.LOGIN_FAILED);
            }
            loginDto.setId(yqzcUser.getUserId());
            Calendar calendar=Calendar.getInstance();
            calendar.add(Calendar.DATE,1);//使token的时间加长为一天
            loginDto.setExp(calendar.getTime());

            String encode= JwtUtil.encode(loginDto);

            return CommonResult.onSuccess(encode);

        } catch (JOSEException e) {
            e.printStackTrace();
        }

        return CommonResult.onFailed(ResultStatus.LOGIN_FAILED);
    }

    @GetMapping("/verificationCode")
    @ResponseBody
    @ApiOperation("获取验证码")
    public CommonResult verificationCode(String phoneNumber) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = shortMessageUtil.createClient("LTAI4G8hZMb8ctRioeMRXDds", "kipijeuePAZgE5rKrHHJngWlP304oZ");
        String code = UUID.randomUUID().toString().replace("-","").substring(0,6);

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumber)
                .setSignName("luc门户")
                .setTemplateCode("SMS_189025605")
                .setTemplateParam("{\"code\":\""+code+"\"}");
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        // 将验证码写入数据库
        if ("OK".equals(sendSmsResponse.getBody().message)){
            Date date = new Date();
            Code code1 = new Code();
            code1.setCode(code);
            code1.setPhoneNumber(phoneNumber);
            code1.setCreatTime(date);

           int row = codeService.addCode(code1);
           return row >0 ?CommonResult.onSuccess(null):CommonResult.onFailed(ResultStatus.GETMESSAGE_FAILED);
        }
        return null;
    }


    @PostMapping("/login-verificationCode")
    @ResponseBody
    @ApiOperation("验证码登录")
    public CommonResult loginByCode(@RequestBody AddLoginByCodeVo addLoginByCodeVo){
        boolean existence = codeService.findCodeByCodeAndPhoneNumber(addLoginByCodeVo.getCode(),addLoginByCodeVo.getPhoneNumber());
        if(existence){
            YqzcUser user = userService.findUserByUserPhoneNumber(addLoginByCodeVo.getPhoneNumber());
            if(user == null){
                user = new YqzcUser();
                user.setUserPhoneNumber(addLoginByCodeVo.getPhoneNumber());
                userService.addUerToSql(user);
            }
            loginDto.setId(user.getUserId());
            //获取当前时间
            Calendar calendar = Calendar.getInstance();
            //从当前时间加一天
            calendar.add(Calendar.DATE,1);
            loginDto.setExp(calendar.getTime());
            String encode = null;
            try {
                encode = JwtUtil.encode(loginDto);
            } catch (JOSEException e) {
                e.printStackTrace();
            }
            return CommonResult.onSuccess(encode);
        }
        return CommonResult.onFailed(ResultStatus.MESSAGE_FAILED);
    }

    @PostMapping("/register")
    @ApiOperation("注册")
//    @RequiresPermissions("user:create")
    public CommonResult register(@RequestBody AddUserVo addUserVo){

        YqzcUser yqzcUser=new YqzcUser();
        BeanUtils.copyProperties(addUserVo,yqzcUser);

        return userService.addUser(yqzcUser);
    }

    @GetMapping("/user/userInfo")
    @ApiOperation("基本资料")
    public CommonResult  userInfo(){
        CompanyInfoDto companyInfoDto=new CompanyInfoDto();
        CompanyInfoBean companyInfoBean=new CompanyInfoBean();

        companyInfoDto.setUserId(loginDto.getId());

        System.out.println(loginDto.getId());
        BeanUtils.copyProperties(companyInfoDto,companyInfoBean);

        CompanyInfoBean companyInfoBean1 = companyService.queryCompanyByUserId(companyInfoBean);

        return  CommonResult.onSuccess(companyInfoBean1) ;
    }

   @PutMapping("/user/{id}")
    @ApiOperation("修改资料")
    public CommonResult editInfo(@RequestBody CompanyInfoEditVo companyInfoEditVo){

        CompanyInfoBean companyInfoBean=new CompanyInfoBean();
        BeanUtils.copyProperties(companyInfoEditVo,companyInfoBean);
       Integer id = loginDto.getId();
       return companyService.updateCompanyInfoById(id,companyInfoBean);
   }
    @GetMapping("/user/invoice")
    @ApiOperation("查询发票")
    public CommonResult invote(){
        YqzcInvoice yqzcInvoice=new YqzcInvoice();
        InvoiceVo invoiceVo=new InvoiceVo();

        invoiceVo.setUserId(loginDto.getId());
        BeanUtils.copyProperties(invoiceVo,yqzcInvoice);

        YqzcInvoice yqzcInvoice1 =invoiceService.queryInvoiceById(yqzcInvoice);

        return CommonResult.onSuccess(yqzcInvoice1);
    }

    @PutMapping("/user/addinvoice")
    @ApiOperation("开具发票")
    public CommonResult addInvoite(@RequestBody InvoiceVo invoiceVo){
        YqzcInvoice yqzcInvoice=new YqzcInvoice();
        BeanUtils.copyProperties(invoiceVo,yqzcInvoice);
        Integer id=loginDto.getId();
        return invoiceService.addInvoiceById(id,yqzcInvoice);
    }
}
